package org.hiberlyzer.ui;

import java.awt.Component;
import java.util.Enumeration;

import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

import org.hiberlyzer.DataSet;
import org.hiberlyzer.DataSource;
import org.hiberlyzer.QueryException;
import org.hiberlyzer.QueryLanguage;

public class ResultView extends JTabbedPane
{
	private DataSetTable resultsTable;
	private JTextArea messagesTextArea;
	private int resultCount = 0;
	
	public ResultView(QueryWindow parentWindow)
	{
		super(JTabbedPane.BOTTOM);
		addTab("Results", buildResultsPanel(parentWindow));
		addTab("Messages", buildMessagePanel());
		showTable();
	}
	
	public void displayResults(String queryString, QueryLanguage queryLanguage, DataSource dataSource)
	{
		TableModel resultsModel = null;
		try
		{
			DataSet dataSet = dataSource.query(queryString, queryLanguage);
			resultsModel = new DataSetTableModel(dataSet);
			messagesTextArea.setText(resultsModel.getRowCount() + " row(s) affected");
			if(resultsModel.getRowCount() > 0)
			{
				showTable();
			}
			else
			{
				showMessages();
			}
		}
		catch (QueryException e)
		{
			displayMessages(e.getMessage());
			resultsModel = new EmptyTableModel();
		}
		
		resultsTable.setModel(resultsModel);
		resultCount = resultsModel.getRowCount();
		for(int i = 0; i < resultsTable.getColumnCount(); i++)
		{
			TableColumn column = resultsTable.getColumnModel().getColumn(i);
			column.setPreferredWidth(200);
		}
		for(Enumeration<TableColumn> columns = resultsTable.getColumnModel().getColumns(); columns.hasMoreElements();)
		{
			columns.nextElement().setPreferredWidth(200);			
		}
	}

	public void displayMessages(String message)
	{
		messagesTextArea.setText(message);
		messagesTextArea.setCaretPosition(0);
		showMessages();
	}
	
	private Component buildResultsPanel(QueryWindow queryWindow)
	{
		resultsTable = new DataSetTable(queryWindow);
		JScrollPane resultsPanel = new JScrollPane(resultsTable);
		resultsPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		resultsPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		return resultsPanel;
	}

	private Component buildMessagePanel()
	{
		messagesTextArea = new JTextArea();
		JScrollPane messagesPanel = new JScrollPane(messagesTextArea);
		return messagesPanel;
	}
	
	private void showTable()
	{
		setSelectedIndex(0);
	}
	
	private void showMessages()
	{
		setSelectedIndex(1);
	}

	public int getResultCount()
	{
		return resultCount;
	}

	public void clear()
	{
		resultCount = 0;
		messagesTextArea.setText("");
		resultsTable.setModel(new EmptyTableModel());
	}
}
